package com.budwk.app.wxprogram.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.miniapp.common.enums.WxEventEnum;
import com.budwk.app.miniapp.models.SysDictData;
import com.budwk.app.miniapp.models.WxEvent;
import com.budwk.app.miniapp.models.dto.SqfwServicerecordDTO;
import com.budwk.app.miniapp.services.ShequUserService;
import com.budwk.app.miniapp.services.SysdictdataService;
import com.budwk.app.miniapp.services.WxeventService;
import com.budwk.app.miniapp.utils.NutzIocUtils;
import com.budwk.app.sys.models.ShequUser;
import com.budwk.app.wxprogram.models.Wx_area;
import com.budwk.app.wxprogram.models.Wx_event;
import com.budwk.app.wxprogram.models.Wx_event_schedule;
import com.budwk.app.wxprogram.models.vx_volunteer;
import com.budwk.app.wxprogram.services.VxVolunteerService;
import com.budwk.app.wxprogram.services.WxEventScheduleService;
import com.budwk.starter.common.exception.BaseException;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.wxprogram.services.WxEventService;
import jodd.io.FileUtil;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@IocBean
@At("/platform/wxprogram/event")
@ApiDefinition(tag = "求救求助信息表")
@Slf4j
public class WxEventController{

    @Inject
    Dao dao;
    @Inject
    private WxEventService wxEventService;

    @Inject
    private WxeventService wxeventService;

    @Inject
    private VxVolunteerService vxVolunteerService;
    @Inject
    private WxEventScheduleService wxEventScheduleService;

    @Inject
    private SysdictdataService sysdictdataService;
    @Inject
    private ShequUserService  shequUserService;
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询求救求助信息表")
    @ApiFormParams(
        value = {
            @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
            @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
            @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
            @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
        },
        implementation = Wx_event.class
    )
    @ApiResponses(
    implementation = Wx_event.class
    )
    //@SaCheckPermission("wxprogram.event")
    public Result<?> list(@Param("..")Wx_event bean,@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }
        
        if (bean.getEvent_title() !=null && Strings.isNotBlank(bean.getEvent_title().toString())) {
            cnd.and("event_title","like","%"+bean.getEvent_title()+"%");
        }
        
        if (bean.getEvent_type() !=null && Strings.isNotBlank(bean.getEvent_type().toString())) {
            cnd.and("event_type","like","%"+bean.getEvent_type()+"%");
        }
        
        if (bean.getEvent_status() !=null && Strings.isNotBlank(bean.getEvent_status().toString())) {
            cnd.and("event_status","like","%"+bean.getEvent_status()+"%");
        }
        
        if (bean.getEvent_phone() !=null && Strings.isNotBlank(bean.getEvent_phone().toString())) {
            cnd.and("event_phone","like","%"+bean.getEvent_phone()+"%");
        }
        
        if (bean.getEvent_content_type() !=null && Strings.isNotBlank(bean.getEvent_content_type().toString())) {
            cnd.and("event_content_type","like","%"+bean.getEvent_content_type()+"%");
        }
        
        if (bean.getEvent_province() !=null && Strings.isNotBlank(bean.getEvent_province().toString())) {
            cnd.and("event_province","like","%"+bean.getEvent_province()+"%");
        }
        
        if (bean.getEvent_city() !=null && Strings.isNotBlank(bean.getEvent_city().toString())) {
            cnd.and("event_city","like","%"+bean.getEvent_city()+"%");
        }
        
        if (bean.getEvent_district() !=null && Strings.isNotBlank(bean.getEvent_district().toString())) {
            cnd.and("event_district","like","%"+bean.getEvent_district()+"%");
        }
        
        if (bean.getEvent_street() !=null && Strings.isNotBlank(bean.getEvent_street().toString())) {
            cnd.and("event_street","like","%"+bean.getEvent_street()+"%");
        }
        
        if (bean.getEvent_address() !=null && Strings.isNotBlank(bean.getEvent_address().toString())) {
            cnd.and("event_address","like","%"+bean.getEvent_address()+"%");
        }
        
        if (bean.getCreate_time() !=null && Strings.isNotBlank(bean.getCreate_time().toString())) {
            Instant instant = bean.getCreate_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("create_time","between",new Object[]{startdateStr,enddateStr});
        }
        
        if (bean.getMsgaudit_pass_time() !=null && Strings.isNotBlank(bean.getMsgaudit_pass_time().toString())) {
            Instant instant = bean.getMsgaudit_pass_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("msgaudit_pass_time","between",new Object[]{startdateStr,enddateStr});
        }
        
        if (bean.getVolunteer_ordertime() !=null && Strings.isNotBlank(bean.getVolunteer_ordertime().toString())) {
            Instant instant = bean.getVolunteer_ordertime().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("volunteer_ordertime","between",new Object[]{startdateStr,enddateStr});
        }
        
        if (bean.getVolunteer_whether_help() !=null && Strings.isNotBlank(bean.getVolunteer_whether_help().toString())) {
            cnd.and("volunteer_whether_help","like","%"+bean.getVolunteer_whether_help()+"%");
        }
        
        if (bean.getSpecial_requirement() !=null && Strings.isNotBlank(bean.getSpecial_requirement().toString())) {
            cnd.and("special_requirement","like","%"+bean.getSpecial_requirement()+"%");
        }
        
        if (bean.getEvent_nickname() !=null && Strings.isNotBlank(bean.getEvent_nickname().toString())) {
            cnd.and("event_nickname","like","%"+bean.getEvent_nickname()+"%");
        }
        
        if (bean.getEvent_sex() !=null && Strings.isNotBlank(bean.getEvent_sex().toString())) {
            cnd.and("event_sex","like","%"+bean.getEvent_sex()+"%");
        }
        
        if (bean.getLongitude() !=null && Strings.isNotBlank(bean.getLongitude().toString())) {
            cnd.and("longitude","like","%"+bean.getLongitude()+"%");
        }
        
        if (bean.getLatitude() !=null && Strings.isNotBlank(bean.getLatitude().toString())) {
            cnd.and("latitude","like","%"+bean.getLatitude()+"%");
        }
        
        if (bean.getVolunteer_name() !=null && Strings.isNotBlank(bean.getVolunteer_name().toString())) {
            cnd.and("volunteer_name","like","%"+bean.getVolunteer_name()+"%");
        }
        
        if (bean.getVolunteer_sex() !=null && Strings.isNotBlank(bean.getVolunteer_sex().toString())) {
            cnd.and("volunteer_sex","like","%"+bean.getVolunteer_sex()+"%");
        }
        
        if (bean.getVolunteer_phone() !=null && Strings.isNotBlank(bean.getVolunteer_phone().toString())) {
            cnd.and("volunteer_phone","like","%"+bean.getVolunteer_phone()+"%");
        }
        
        if (bean.getVolunteer_year() !=null && Strings.isNotBlank(bean.getVolunteer_year().toString())) {
            cnd.and("volunteer_year","like","%"+bean.getVolunteer_year()+"%");
        }
        
        if (bean.getVolunteer_complete_num() !=null && Strings.isNotBlank(bean.getVolunteer_complete_num().toString())) {
            cnd.and("volunteer_complete_num","like","%"+bean.getVolunteer_complete_num()+"%");
        }
        
        if (bean.getOpenid() !=null && Strings.isNotBlank(bean.getOpenid().toString())) {
            cnd.and("openid","like","%"+bean.getOpenid()+"%");
        }
        
        if (bean.getUser_name() !=null && Strings.isNotBlank(bean.getUser_name().toString())) {
            cnd.and("user_name","like","%"+bean.getUser_name()+"%");
        }
        
        if (bean.getEvent_content() !=null && Strings.isNotBlank(bean.getEvent_content().toString())) {
            cnd.and("event_content","like","%"+bean.getEvent_content()+"%");
        }
        
        if (bean.getEvent_pic_url() !=null && Strings.isNotBlank(bean.getEvent_pic_url().toString())) {
            cnd.and("event_pic_url","like","%"+bean.getEvent_pic_url()+"%");
        }
        
        if (bean.getCreate_by() !=null && Strings.isNotBlank(bean.getCreate_by().toString())) {
            cnd.and("create_by","like","%"+bean.getCreate_by()+"%");
        }
        
        if (bean.getUpdate_by() !=null && Strings.isNotBlank(bean.getUpdate_by().toString())) {
            cnd.and("update_by","like","%"+bean.getUpdate_by()+"%");
        }
        
        if (bean.getUpdate_time() !=null && Strings.isNotBlank(bean.getUpdate_time().toString())) {
            cnd.and("update_time","like","%"+bean.getUpdate_time()+"%");
        }
        
        if (bean.getRemark() !=null && Strings.isNotBlank(bean.getRemark().toString())) {
            cnd.and("remark","like","%"+bean.getRemark()+"%");
        }
        
        if (bean.getEvent_create_time() !=null && Strings.isNotBlank(bean.getEvent_create_time().toString())) {
            Instant instant = bean.getEvent_create_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("event_create_time","between",new Object[]{startdateStr,enddateStr});
        }
        
        if (bean.getEvent_complete_time() !=null && Strings.isNotBlank(bean.getEvent_complete_time().toString())) {
            Instant instant = bean.getEvent_complete_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("event_complete_time","between",new Object[]{startdateStr,enddateStr});
        }
        
        if (bean.getEvent_reminder() !=null && Strings.isNotBlank(bean.getEvent_reminder().toString())) {
            cnd.and("event_reminder","like","%"+bean.getEvent_reminder()+"%");
        }
        
        if (bean.getEvent_priority() !=null && Strings.isNotBlank(bean.getEvent_priority().toString())) {
            cnd.and("event_priority","like","%"+bean.getEvent_priority()+"%");
        }
        
        if (bean.getEvent_label() !=null && Strings.isNotBlank(bean.getEvent_label().toString())) {
            cnd.and("event_label","like","%"+bean.getEvent_label()+"%");
        }
        
        if (bean.getOrder_by() !=null && Strings.isNotBlank(bean.getOrder_by().toString())) {
            cnd.and("order_by","like","%"+bean.getOrder_by()+"%");
        }
        
        if (bean.getEvent_reminder_status() !=null && Strings.isNotBlank(bean.getEvent_reminder_status().toString())) {
            cnd.and("event_reminder_status","like","%"+bean.getEvent_reminder_status()+"%");
        }
        
        if (bean.getEvent_sys_status() !=null && Strings.isNotBlank(bean.getEvent_sys_status().toString())) {
            cnd.and("event_sys_status","like","%"+bean.getEvent_sys_status()+"%");
        }
        
        if (bean.getEvent_index() !=null && Strings.isNotBlank(bean.getEvent_index().toString())) {
            cnd.and("event_index","like","%"+bean.getEvent_index()+"%");
        }
        
        if (bean.getEvent_video() !=null && Strings.isNotBlank(bean.getEvent_video().toString())) {
            cnd.and("event_video","like","%"+bean.getEvent_video()+"%");
        }
        
        if (bean.getEvent_followers() !=null && Strings.isNotBlank(bean.getEvent_followers().toString())) {
            cnd.and("event_followers","like","%"+bean.getEvent_followers()+"%");
        }
        
        if (bean.getEvent_properties() !=null && Strings.isNotBlank(bean.getEvent_properties().toString())) {
            cnd.and("event_properties","like","%"+bean.getEvent_properties()+"%");
        }
        
        if (bean.getEvent_nature() !=null && Strings.isNotBlank(bean.getEvent_nature().toString())) {
            cnd.and("event_nature","like","%"+bean.getEvent_nature()+"%");
        }
        
        if (bean.getEvent_role() !=null && Strings.isNotBlank(bean.getEvent_role().toString())) {
            cnd.and("event_role","like","%"+bean.getEvent_role()+"%");
        }
        
        if (bean.getEvent_top() !=null && Strings.isNotBlank(bean.getEvent_top().toString())) {
            cnd.and("event_top","like","%"+bean.getEvent_top()+"%");
        }
        
        if (bean.getEvent_adcode() !=null && Strings.isNotBlank(bean.getEvent_adcode().toString())) {
            cnd.and("event_adcode","like","%"+bean.getEvent_adcode()+"%");
        }
        
        if (bean.getEvent_area_type() !=null && Strings.isNotBlank(bean.getEvent_area_type().toString())) {
            cnd.and("event_area_type","like","%"+bean.getEvent_area_type()+"%");
        }
        
        if (bean.getAuditing_type() !=null && Strings.isNotBlank(bean.getAuditing_type().toString())) {
            cnd.and("auditing_type","like","%"+bean.getAuditing_type()+"%");
        }
        
        if (bean.getComplete_type() !=null && Strings.isNotBlank(bean.getComplete_type().toString())) {
            cnd.and("complete_type","like","%"+bean.getComplete_type()+"%");
        }


        
        return Result.data(wxEventService.listPage(pageNo, pageSize, cnd));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增求救求助信息表")
    @ApiFormParams(
        implementation = Wx_event.class
    )
    @ApiResponses
    @SLog(tag = "新增求救求助信息表", value = "${args[0].id}")
    @SaCheckPermission("wxprogram.event.create")
    public Result<?> create(@Param("..")Wx_event wxEvent, HttpServletRequest req) {
        wxEvent.setCreatedBy(SecurityUtil.getUserId());
        wxEventService.insert(wxEvent);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改求救求助信息表")
    @ApiFormParams(
        implementation = Wx_event.class
    )
    @ApiResponses
    @SLog(tag = "修改求救求助信息表", value = "${args[0].id}")
    @SaCheckPermission("wxprogram.event.update")
    public Result<?> update(@Param("..")Wx_event wxEvent, HttpServletRequest req) {
        wxEvent.setUpdatedBy(SecurityUtil.getUserId());
        wxEventService.updateIgnoreNull(wxEvent);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取求救求助信息表")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    @SaCheckPermission("wxprogram.event")
    public Result<?> getData(@Param("id")String id, HttpServletRequest req) {
        Wx_event wxEvent = wxEventService.fetch(id);
        if (wxEvent == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data(wxEvent);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除求救求助信息表")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    @SLog(tag = "删除求救求助信息表", value = "${args[0]}")
    @SaCheckPermission("wxprogram.event.delete")
    public Result<?> delete(@Param("id")String id, HttpServletRequest req) {
        Wx_event wxEvent = wxEventService.fetch(id);
        if (wxEvent == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        wxEventService.delete(id);
        req.setAttribute("_slog_msg", wxEvent.getId());
        return Result.success();
    }




    @At("/passCheck")
    @Ok("json")
    @POST
    @ApiOperation(name = "审核通过")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "Y", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event.passCheck")
    public Result<?> passCheck(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

        //如果是求助
        if (eventType.equals("natural_disaster")) {
            Sql sql = Sqls.create("update  wx_event set event_status='Y',msgaudit_pass_time='"+new Date()+"' where id='" + id + "'");
            dao.execute(sql);
            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("您的求助信息已通过审核，祥云AI正在为您找寻志愿者");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

        }


        //如果是求救
        if (eventType.equals("emergency_events")) {
            Sql sql = Sqls.create("update  wx_event set event_status='Y',msgaudit_pass_time='"+new Date()+"' where id='" + id + "'");
            dao.execute(sql);
            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("您的求救信息已通过审核，祥云AI正在为您找寻专业救援人员");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

        }


        return  Result.success();
    }

    @At("/noPass")
    @Ok("json")
    @POST
    @ApiOperation(name = "审核不通过")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "not_approved", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event.noPass")
    public Result<?> noPass(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

        //如果是求助
        if (eventType.equals("natural_disaster")) {
            Sql sql = Sqls.create("update  wx_event set event_status='not_approved' where id='" + id + "'");
            dao.execute(sql);
            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("您的求助信息审核未通过，重新发起申请");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));
            wxEventScheduleService.insert(wx_event_schedule);

        }

        //如果是求救
        if (eventType.equals("emergency_events")) {
            Sql sql = Sqls.create("update  wx_event set event_status='not_approved' where id='" + id + "'");
            dao.execute(sql);
            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("您的求救信息审核未通过，重新发起申请");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

        }


        return  Result.success();
    }

    @At("/matchSucceed")
    @Ok("json")
    @POST
    @ApiOperation(name = "匹配成功")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "matching", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event")
    public Result<?> matchSucceed(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

        //如果是求助
        if (eventType.equals("natural_disaster")) {
            Sql sql = Sqls.create("update  wx_event set event_status='matching' where id='" + id + "'");
            dao.execute(sql);
            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("正在通知志愿者");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);


            // TODO: 2023/4/13
           /* 4-1-2.求助信息与志愿者信息之间的匹配逻辑：*/


        }

        //如果是求救
        if (eventType.equals("emergency_events")) {
            Sql sql = Sqls.create("update  wx_event set event_status='matching' where id='" + id + "'");
            dao.execute(sql);
            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("正在通知救援队，请耐心等待");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

        }


        return  Result.success();
    }


    @At("/matchFail")
    @Ok("json")
    @POST
    @ApiOperation(name = "匹配失败")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "match_failed", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event")
    public Result<?> matchFail(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

        //如果是求助
        if (eventType.equals("natural_disaster")) {
            Sql sql = Sqls.create("update  wx_event set event_status='match_failed' where id='" + id + "'");
            dao.execute(sql);
            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("很抱歉，当前暂无志愿者，您的信息将展示在首页等待志愿者为您提供帮助");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

            // TODO: 2023/4/13
            /* 4-1-2.求助信息与志愿者信息之间的匹配逻辑：*/

        }


        // TODO: 2023/4/13
        //求救没有匹配逻辑


        return  Result.success();
    }


    @At("/waitHelp")
    @Ok("json")
    @POST
    @ApiOperation(name = "待帮助")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "pending_evaluation", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event")
    public Result<?> waitHelp(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

        //如果是求助
        if (eventType.equals("natural_disaster")) {
            Sql sql = Sqls.create("update  wx_event set event_status='pending_evaluation' where id='" + id + "'");
            dao.execute(sql);

            List<Wx_event> fetch=dao.query(Wx_event.class,Cnd.where("id","=",id));
            String phone=fetch.get(0).getVolunteer_phone().substring(7);

            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("尾号'"+phone+"'的祥云志愿者已接受你的求助，请保持手机畅通，等待志愿者电话");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));


            wxEventScheduleService.insert(wx_event_schedule);

            // TODO: 2023/4/13
            /* 6-1-2*/
            mathtingWait5min(id,eventType,eventStatus);


        }


        //如果是求救
        if (eventType.equals("emergency_events")) {
            Sql sql = Sqls.create("update  wx_event set event_status='pending_evaluation' where id='" + id + "'");
            dao.execute(sql);

            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("救援人员将为您提供救援，请保持手机畅通");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

            // TODO: 2023/4/13
            /* 6-1-2*/
            mathtingWait5min(id,eventType,eventStatus);

        }


        return  Result.success();
    }


    @At("/matching")
    @Ok("json")
    @POST
    @ApiOperation(name = "匹配")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "matching", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event")
    //志願者匹配 ///* 4-1-2.求助信息与志愿者信息之间的匹配逻辑：*/     /* 4-1-2.求助信息与志愿者信息之间的匹配逻辑：*/
    public Result<?> matching(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {
        Cnd cnd = Cnd.NEW();
        cnd.and("id","=",id);
       List<Wx_event>  list =wxEventService.query(cnd);
       if(list.size()>0){

           SqlExpressionGroup e1 = Cnd.exps("cities", "LIKE", "全部%").or("cities", "=", list.get(0).getEvent_city());
           SqlExpressionGroup e2 = Cnd.exps("districts", "LIKE", "全部%").or("districts", "=", list.get(0).getEvent_district());
           SqlExpressionGroup e3 = Cnd.exps("townships", "LIKE", "全部%").or("townships", "=", list.get(0).getEvent_street());
           SqlExpressionGroup e4 = Cnd.exps("provinces", "=", list.get(0).getEvent_province());

           //意向服务时间
          String week = this.getWeek(list.get(0).getCreate_time());
           if(week!=null)
           {
               e4.and("servicetime","like","%"+week+"%");
           }
           if(list.get(0).getEvent_label()!=null)
           {
               if(list.get(0).getEvent_label().equals("我是女生，需要女性志愿者"))
               {
                   e4.and("sexual ","=","女");
               }
               if(list.get(0).getEvent_label().equals("我是男生，需要男性志愿者"))
               {
                   e4.and("sexual ","=","男");
               }
               if(list.get(0).getEvent_label().equals("我是残疾人"))
               {
                   e4.and("sexual ","=","男");
               }
               if(list.get(0).getEvent_label().equals("我是老年人"))
               {
                   e4.and("years ","<","1993"); //大于30岁
               }
               if(list.get(0).getEvent_label().equals("我是孕妇"))
               {
                   e4.and("sexual ","=","女");
               }

           }

           Cnd ccnd = Cnd.NEW();
           Condition c = ccnd.where(e1).and(e2).and(e3).and(e4).asc("provinces");
           List<vx_volunteer>  vlist = vxVolunteerService.query(c);

          // List<vx_volunteer>  vlist = vxVolunteerService.query(vcnd);

               if(vlist.size()>0)
               {
                    // ④如果匹配成功，即“事件管理数据库”比对“志愿者数据库”找到符合志愿者时，则“信息状态”变为“匹配成功”；

                       //如果是求助
                       if (eventType.equals("natural_disaster")) {
                           Sql sql = Sqls.create("update  wx_event set event_status='matching' where id='" + id + "'");
                           dao.execute(sql);
                           Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
                           wx_event_schedule.setEvent_id(id);
                           wx_event_schedule.setEvent_status("matching");
                           wx_event_schedule.setEvent_type(eventType);
                           wx_event_schedule.setEvent_content("正在通知志愿者");
                           //wx_event_schedule.setCreatedBy(SecurityUtil.getUserId());
                           SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                           wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

                           wxEventScheduleService.insert(wx_event_schedule);
                            // 微信推送消
                           try {
                                   Date createTime =list.get(0).getCreate_time();
                                   for (int i = 0; i < vlist.size(); i++) {
                                        //服务时间
                                       Boolean times= getScopeTimes(vlist.get(i),week,createTime); //获取服务时间段匹配
                                       if(times) {
//                                           pullmsg(vlist.get(i).getOpenid(), list.get(0).getId());
                                           wxeventService.sendMessage(vlist.get(i).getOpenid(), list.get(0).getId());
                                       }

                                   }

                           } catch(Exception e) {
                               System.out.println("微信推送消息失败！");
                               e.printStackTrace();
                           }

                         //4-1-3.当前时间减去“匹配成功状态改变时间”大于五分钟时，将“信息状态”、“当前时间”以及文案“很抱歉，当前暂无志愿者，您的信息将展示在首页等待志愿者为您提供帮助”推送到小程序；
                           mathtingWait5min(id,eventType,eventStatus);

                       }

                       //如果是求救
                       if (eventType.equals("emergency_events")) {
                           Sql sql = Sqls.create("update  wx_event set event_status='matching' where id='" + id + "'");
                           dao.execute(sql);
                           Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
                           wx_event_schedule.setEvent_id(id);
                           wx_event_schedule.setEvent_status("matching");
                           wx_event_schedule.setEvent_type(eventType);
                           wx_event_schedule.setEvent_content("正在通知救援队，请耐心等待");
                           //wx_event_schedule.setCreatedBy(SecurityUtil.getUserId());
                           SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                           wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

                           wxEventScheduleService.insert(wx_event_schedule);

                       }



                   return Result.success(0,"成功");
               }
               else
               {

                   // ⑤如果匹配不成功，即“事件管理数据库”比对“志愿者数据库”未找到符合志愿者时，则“信息状态”变为“匹配失败”；
                   //如果是求助
                   if (eventType.equals("natural_disaster")) {
                       Sql sql = Sqls.create("update  wx_event set event_status='match_failed' where id='" + id + "'");
                       dao.execute(sql);
                       Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
                       wx_event_schedule.setEvent_id(id);
                       wx_event_schedule.setEvent_status("match_failed");
                       wx_event_schedule.setEvent_type(eventType);
                       wx_event_schedule.setEvent_content("很抱歉，当前暂无志愿者，您的信息将展示在首页等待志愿者为您提供帮助");
                       //wx_event_schedule.setCreatedBy(SecurityUtil.getUserId());
                       SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                       wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

                       wxEventScheduleService.insert(wx_event_schedule);
                   }

                   //如果是求救 求救信息没有“匹配失败”状态；
                   return Result.success(1,"失败");

               }


       }

        return  Result.success();
    }


    @At("/matchingToUser")
    @Ok("json")
    @POST
    @ApiOperation(name = "匹配指定人员")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "matching", description = "事件状态")

            }
    )
    //@SaCheckPermission("wxprogram.event")
    public Result<?> matchingToUser(@Param("id")String id) {
        WxEvent wxEvent =wxeventService.fetch(id);
        if(!wxEvent.getEventStatus().equals("Y")){
            throw new BaseException(id+"不处于匹配状态");
        }
        SysDictData dictDataList=  sysdictdataService.fetch(Cnd.where(SysDictData::getDictType,"=","help_content_type")
                .and(SysDictData::getDictValue,"=",wxEvent.getEventContentType()));
        String getJwtTokenUrl= NutzIocUtils.getPropertiesProxy().get("app.getJwtToken");
        String genTokenByPhoneUrl= NutzIocUtils.getPropertiesProxy().get("app.genTokenByPhone");
        HashMap<String, Object> paramMap = new HashMap<>();
        Result result = JSONUtil.toBean(HttpUtil.post(getJwtTokenUrl, paramMap),Result.class);
        if(!result.isSuccess()){
            return  Result.error(result.toString());
        }
        String jwtToken= (String) result.getData();
        paramMap.put("phone", WxEventEnum.getPhoneByCommunity(wxEvent.getCommunity()));
        paramMap.put("jwtToken",jwtToken);
        Result result2 = JSONUtil.toBean(HttpUtil.post(genTokenByPhoneUrl, paramMap),Result.class);
        if(!result2.isSuccess()){
            return  Result.error(result2.toString());
        }
        ShequUser user= shequUserService.fetch(Cnd.where(ShequUser::getLoginname,"=",WxEventEnum.getPhoneByCommunity(wxEvent.getCommunity())));
        if(ObjectUtil.isEmpty(user)){
            throw new BaseException("手机号未注册:"+WxEventEnum.getPhoneByCommunity(wxEvent.getCommunity()));
        }
        String token= (String) result2.getData();
        String servicerecordCreateUrl= NutzIocUtils.getPropertiesProxy().get("app.servicerecordCreate");
        String title = StrFormatter.format("【社区求助】{}", wxEvent.getEventTitle() );
        String content = StrFormatter.format("\n求助人：{}\n求助类型：{}\n需要帮助内容：{}\n联系方式：{}\n求助地址：{}\n安全防范特殊需求：{}", wxEvent.getUserName(),dictDataList.getDictLabel(),wxEvent.getEventTitle(),wxEvent.getEventPhone(),wxEvent.getEventAddress(),wxEvent.getEventLabel());
        SqfwServicerecordDTO servicerecordDTO=new SqfwServicerecordDTO(user,wxEvent.getId(),title,content);
        Result result3 = JSONUtil.toBean(HttpRequest.post(servicerecordCreateUrl).header("wk-user-token",token).body(JSONUtil.toJsonStr(servicerecordDTO)).execute().body(),Result.class);
        if(!result3.isSuccess()){
            return  Result.error(result3.toString());
        }
        insertEventSchedule(wxEvent,user);
        return  Result.success();
    }

    private void insertEventSchedule(WxEvent wxEvent, ShequUser user){
        List<Wx_event_schedule> list=new ArrayList<>();
        Wx_event_schedule a = new Wx_event_schedule();
        a.setEvent_id(wxEvent.getId());
        a.setEvent_status("matching");
        a.setEvent_type(wxEvent.getEventType());
        a.setEvent_content("正在通知社区工作人员");
        a.setEvent_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        wxEventScheduleService.insert(a);
        Wx_event_schedule c = new Wx_event_schedule();
        c.setEvent_id(wxEvent.getId());
        c.setEvent_status("pending_evaluation");
        c.setEvent_type(wxEvent.getEventType());
        c.setEvent_content("尾号"+user.getLoginname().substring(user.getLoginname().length() - 4)+"的社区工作人员已接受你的求助，请保持手机畅通，等待社区工作人员电话");
        c.setEvent_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        wxEventScheduleService.insert(c);

        Sql sql = Sqls.create("update  wx_event set event_status='pending_evaluation' where id='" + wxEvent.getId() + "'");
        dao.execute(sql);
    }

    public  boolean getScopeTimes(vx_volunteer  volunteer,String week,Date Create_time)
    {
        boolean reslut=false;
        try {
                String servicetime = volunteer.getServicetime().substring(volunteer.getServicetime().indexOf(week) + 3);
                servicetime =volunteer.getServicetime().substring(3, volunteer.getServicetime().indexOf(",")).replace(" ", "");
                String[] servicetimelist = servicetime.split("-");
                Integer bigin = Integer.valueOf(servicetimelist[0].substring(0, 2)), end = Integer.valueOf(servicetimelist[1].substring(0, 2));
                Integer hours = Create_time.getHours();

                if (hours >= bigin    && end >= hours)  //服务时间段
                {
                    reslut=true;
                   // pullmsg(vlist.get(i).getOpenid(), list.get(0).getId());
                }

        } catch(Exception e) {
            System.out.println("服务时间段匹配失败！");
            e.printStackTrace();
        }

        return  reslut;
    }



    //推送志愿者接单的服务号消息，
    public  void pullmsg(String openId,String eventId)
    {
        try {
            if (openId==null||eventId==null){
                System.out.println("事件id或openid为空！");
                return;
            }
            String requestUrl = "http://140.210.211.155:10086/weixin/event/eventSendMessage";
            JSONObject requestUrlParam = new JSONObject();
            //openId
            requestUrlParam.put("openId",openId);
            //eventId
            requestUrlParam.put("eventId",eventId);
            String result = HttpUtil.get(requestUrl,requestUrlParam);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msg = jsonObject.getString("msg");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }


    //根据日期取得星期几
    public static String getWeek(Date date){
        String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }
        return weeks[week_index];
    }



    @Async
    //跑5分钟 //.当前时间减去“匹配成功状态改变时间”大于五分钟时，将“信息状态”、“当前时间”以及文案“很抱歉，当前暂无志愿者，您的信息将展示在首页等待志愿者为您提供帮助”推送到小程序；
    public Result<?> mathtingWait5min(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

            try {
                //将5分钟转换为毫秒
                long waitingTime = 5 * 60 * 1000;
                Thread.sleep(waitingTime);
            } catch (InterruptedException e) {
                //处理异常
            }
            Wx_event wxEvent = wxEventService.fetch(id);
            if (wxEvent != null&&wxEvent.getEvent_status().equals("matching")) {
                    //如果是求助
                    if (eventType.equals("natural_disaster")) {
                        Sql sql = Sqls.create("update  wx_event set event_status='match_failed' where id='" + id + "'");
                        dao.execute(sql);

                        Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
                        wx_event_schedule.setEvent_id(id);
                        wx_event_schedule.setEvent_type(eventType);
                        wx_event_schedule.setEvent_status("match_failed");
                        wx_event_schedule.setEvent_content("很抱歉，当前暂无志愿者，您的信息将展示在首页等待志愿者为您提供帮助");
                        wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));
                        wxEventScheduleService.insert(wx_event_schedule);
                    }


            }
        if (wxEvent != null&&wxEvent.getEvent_status().equals("pending_evaluation"))
            {
                //如果是求助
                if (eventType.equals("natural_disaster")) {
                    Sql sql = Sqls.create("update  wx_event set event_status='pending_evaluation' where id='" + id + "'");
                    dao.execute(sql);

                    Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
                    wx_event_schedule.setEvent_id(id);
                    wx_event_schedule.setEvent_type(eventType);
                    wx_event_schedule.setEvent_status("pending_evaluation");
                    wx_event_schedule.setEvent_content("志愿者是否已为您提供帮助，是或否");
                    wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));
                    wxEventScheduleService.insert(wx_event_schedule);
                }
                //如果是求救
                if (eventType.equals("emergency_events")) {
                    Sql sql = Sqls.create("update  wx_event set event_status='pending_evaluation' where id='" + id + "'");
                    dao.execute(sql);

                    Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
                    wx_event_schedule.setEvent_id(id);
                    wx_event_schedule.setEvent_type(eventType);
                    wx_event_schedule.setEvent_status("pending_evaluation");
                    wx_event_schedule.setEvent_content("救援人员是否已联系您，是或否");
                    wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));
                    wxEventScheduleService.insert(wx_event_schedule);
                }

        }

        return  Result.success();
    }



    @At("/complete")
    @Ok("json")
    @POST
    @ApiOperation(name = "已完成")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "finished", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event")
    public Result<?> complete(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

        //如果是求助
        if (eventType.equals("natural_disaster")) {
            Sql sql = Sqls.create("update  wx_event set event_status='finished' where id='" + id + "'");
            dao.execute(sql);

            List<Wx_event> fetch=dao.query(Wx_event.class,Cnd.where("id","=",id));
            String phone=fetch.get(0).getVolunteer_phone().substring(7);

            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("感谢您对祥云志愿者的支持");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));


            wxEventScheduleService.insert(wx_event_schedule);

            // TODO: 2023/4/13
            /* 7-1-2*/

        }


        //如果是求救
        if (eventType.equals("emergency_events")) {
            Sql sql = Sqls.create("update  wx_event set event_status='finished' where id='" + id + "'");
            dao.execute(sql);

            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("感谢您对救援人员的支持");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

            // TODO: 2023/4/13
            /* 7-2-2*/

        }


        return  Result.success();
    }

    @At("/cancel")
    @Ok("json")
    @POST
    @ApiOperation(name = "已取消")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", example = "1637980737219477506", description = "id"),
                    @ApiFormParam(name = "eventType", example = "natural_disaster", description = "事件分类"),
                    @ApiFormParam(name = "eventStatus", example = "canceled", description = "事件状态")

            }
    )
    @SaCheckPermission("wxprogram.event")
    public Result<?> cancel(@Param("id")String id,@Param("eventType")String  eventType,@Param("eventStatus")String  eventStatus) {

        //如果是求助
        if (eventType.equals("natural_disaster")) {
            Sql sql = Sqls.create("update  wx_event set event_status='canceled' where id='" + id + "'");
            dao.execute(sql);

            List<Wx_event> fetch=dao.query(Wx_event.class,Cnd.where("id","=",id));
            String phone=fetch.get(0).getVolunteer_phone().substring(7);

            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("您已经取消本次求助，感谢您对祥云AI的信任");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));


            wxEventScheduleService.insert(wx_event_schedule);


        }


        //如果是求救
        if (eventType.equals("emergency_events")) {
            Sql sql = Sqls.create("update  wx_event set event_status='canceled' where id='" + id + "'");
            dao.execute(sql);

            Wx_event_schedule wx_event_schedule = new Wx_event_schedule();
            wx_event_schedule.setEvent_id(id);
            wx_event_schedule.setEvent_type(eventType);
            wx_event_schedule.setEvent_status(eventStatus);
            wx_event_schedule.setEvent_content("您已经取消本次求救，感谢您对祥云AI的信任");
            wx_event_schedule.setCreatedBy(SecurityUtil.getUserUsername());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wx_event_schedule.setEvent_time(simpleDateFormat.format(new Date()));

            wxEventScheduleService.insert(wx_event_schedule);

        }


        return  Result.success();
    }



    }
